import http.client
import json
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility
import datetime

# 获取智能柜列表
def doGetcabinetList():
   try:
      logger.info('141:获取智能柜列表');
      httpconn = http.client.HTTPSConnection(global_url)
      payload = ''
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey
      }
      httpconn.request("GET", "/openapi/cabinet/list?query=&pageNo=1&pageSize=200&options=34", payload, headers)
      res = httpconn.getresponse()
      data = res.read()
      data = data.decode("utf-8")
      #print(data)
      #logger.info('141:' + data.decode("utf-8"))
      httpconn.close()

      json_str = json.loads(data)
      ierrCode = json_str["errCode"]
      if(ierrCode==200):
         # 查询当前智能柜数据
         sql = " select foperator from i_ts_cabinet"
         sql = sql + " where fsite_no='" + global_site + "'"
         logger.info('141:' + sql)
         conn, cursor = postsql_utility.get_conn()
         data_2 = postsql_utility.select(sql=sql, cursor=cursor)
         sqllist = []

         # 遍历当前获取的数据
         for j1 in range(len(json_str["data"])):
            # print(json_str["data"][j1], end="\n")
            ibox_exists = False
            ibox_id = json_str["data"][j1]["id"]
            ibox_code = json_str["data"][j1]["code"]
            ibox_name = json_str["data"][j1]["name"]
            ibox_flag = json_str["data"][j1]["cabinetMold"]-1  # 柜子模式（1:RFID柜，2:条码柜）
            ibox_point=""
            try:
               ibox_point = str(json_str["data"][j1]["localeId"])
            except Exception as e:
               print(e)

            ibox_mac = json_str["data"][j1]["md5Code"]
            ibox_dep  = json_str["data"][j1]["departmentId"]

            for j2 in range(len(data_2)):
               if (str(data_2[j2][0]) == str(ibox_id)):
                  ibox_exists = True
                  break

            if (ibox_exists == False):
               sql = "insert into i_ts_cabinet(fsite_no,feuipmentid,fstorageflag,fequipmentbarcode,fequipmenttag"
               sql = sql + ",flabeltype,fstate,fupddate,foperator,fmacno"
               sql = sql + ",fpoint_no,fdangecabinet,fstockno,fpoint_size) "
               sql = sql + "values('" + global_site + "',155,11,'" + ibox_mac + "','" + ibox_name + "'"
               sql = sql + "," + str(ibox_flag) + ",1,now(),"+str(ibox_id)+",'" + ibox_code + "'"
               sql = sql + ",'" + ibox_point + "',0,0,"+str(ibox_dep)+");"
               sqllist.append(sql)
      else:
         print(json_str["errMsg"])

      # 是否有新智能柜资料
      if (len(sqllist)>0):
         i = postsql_utility.executemuch(sqllist, cursor=cursor, connect=conn)

         if i != "OK":
            print(f"失败: {i}")
         else:
            print(f"成功: {i}")
      else:
         print("没有新智能柜数据")

   except Exception as e:
      logger.info('141:错误'+str(e))

#查询智能柜库存汇总
def doGetcabInv():
   try:
      logger.info('152:查询智能柜库存汇总')

      # 查询当前智能柜数据
      sql = " select foperator,fequipmentbarcode from i_ts_cabinet"
      sql = sql + " where fsite_no='" + global_site + "'"
      logger.info('152:' + sql)
      conn, cursor = postsql_utility.get_conn()
      data_2 = postsql_utility.select(sql=sql, cursor=cursor)
      sqllist = []

      for j1 in range(len(data_2)):
         ibox_id = data_2[j1][0]
         ibox_code=data_2[j1][1]

         sql="delete from i_warehouse_inv"
         sql=sql +" where fsite_no='" + global_site + "'"
         sql=sql +" and fcabbarcode='"+str(ibox_code)+"';"
         sqllist.append(sql)

         try:
            httpconn = http.client.HTTPSConnection(global_url)
            payload = ''
            headers = {
               'app-id': global_appid,
               'app-key': global_appkey
            }
            httpconn.request("GET", "/openapi/cabinet/inventory?cabinetId="+str(ibox_id)+"&doorId=", payload, headers)
            res = httpconn.getresponse()
            data = res.read()
            data = data.decode("utf-8")
            #print(data.decode("utf-8"))
            # logger.info('152:' + data.decode("utf-8"))
            httpconn.close()

            # 遍历当前获取的数据,i_warehouse_inv
            json_str = json.loads(data)
            ierrCode = json_str["errCode"]
            if(ierrCode==200):
               irec_num = json_str["data"]["total"]
               if (irec_num > 0):
                  for j1 in range(len(json_str["data"]["datas"])):
                     data_3 = json_str["data"]["datas"][j1]
                     # print(data_3, end="\n")
                     irfid = data_3["data"][0]["rfidCode"]
                     igood_no = data_3["data"][0]["info"]["id"]
                     iweight = data_3["data"][0]["info"]["weight"]
                     timestamp1 = data_3["data"][0]["firstTime"]
                     timestamp2 = str(timestamp1)[:10]  # 前１０位就是时间戳
                     # print(timestamp2)
                     procdate = datetime.datetime.fromtimestamp(int(timestamp2)).strftime('%Y-%m-%d %H:%M:%S')

                     sql = "insert into i_warehouse_inv(fsite_no,fboxbarcode,fcabbarcode,fbatch,frfidbarcode"
                     sql = sql + ",fgoodno,fqty,fstate,fprocdate,fupddate,foperator) "
                     sql = sql + "values('" + global_site + "',0,'" + str(
                        ibox_code) + "','" + irfid + "','" + irfid + "'"
                     sql = sql + "," + str(igood_no) + "," + str(iweight) + ",1,'" + str(procdate) + "',now(),0);"
                     sqllist.append(sql)
               else:
                  print(f"没有库存数据:{ibox_id}")
            else:
               print(json_str["errMsg"])

         except Exception as e:
            logger.info('152:错误1'+str(e))

         if (len(sqllist) > 0):
            i = postsql_utility.executemuch(sqllist, cursor=cursor, connect=conn)

            if i != "OK":
               logger.info('152:失败' + str(i))
            else:
               logger.info('152:成功' + str(i))
         else:
            #print("没有库存数据")
            logger.info('152:没有库存数据')

   except Exception as e:
      logger.info('152:错误2' + str(e))

#
#doGetcabInv()